from typing import List

import face_recognition
import numpy as np
import cv2


class faceSimCalUtils:

    @classmethod
    def calSimDis(cls, comparedfaceVector: list, faceVector):
        return face_recognition.face_distance(comparedfaceVector, faceVector)

    @classmethod
    def getSimFace(cls, comparedfaceVector: list, faceVector):
        newFaceVector=[item for item in comparedfaceVector if item is not None]
        scoreArray=cls.calSimDis(newFaceVector, faceVector)
        bestIndex=np.argmin(scoreArray)
        bestScore=scoreArray[bestIndex]
        return bestIndex,bestScore

    @classmethod
    def getFaceVectors(cls, imgs: List[str]):
        resultVector = []
        for imageItem in imgs:
            loadedImg = face_recognition.load_image_file(imageItem)
            resultVector.append(face_recognition.face_encodings(loadedImg)[0])
        return resultVector

    @classmethod
    def getFaceVector(cls, img: str):

        loadedImg = face_recognition.load_image_file(img)
        faceEncodings = face_recognition.face_encodings(loadedImg)
        if faceEncodings is not None and len(faceEncodings) > 0:
            return faceEncodings[0]
        else:
            return None

    @classmethod
    def drawFaceKeyPoint(self, imgPath: str, outPath: str):
        image = face_recognition.load_image_file(imgPath)
        face_landmarks_list = face_recognition.face_landmarks(image)[0]
        print(face_landmarks_list)
        img = cv2.imread(imgPath)

        facePointKey = ['chin', 'left_eyebrow', 'right_eyebrow', 'nose_bridge', 'nose_tip', 'left_eye', 'right_eye',
                        'top_lip', 'bottom_lip']

        for keyItem in facePointKey:
            prePoint = None

            for item in face_landmarks_list[keyItem]:
                cv2.circle(img, item, 2, (0, 0, 255), thickness=cv2.FILLED)
                if prePoint is not None:
                    cv2.line(img, prePoint, item, (0, 255, 0))
                prePoint = item

        cv2.imwrite(outPath, img)


# faceSimCalUtils.drawFaceKeyPoint("../data/xq.jpeg")
